package com.chixing.controller;

import com.chixing.pojo.Customer;
import com.chixing.service.LoginAndRegisterService;
import com.chixing.util.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Controller
public class LoginAndRegisterController {

    @Autowired
    private LoginAndRegisterService loginAndRegisterService;

    /*
        1.获得客户端参数
        2.调用service
        3.数据绑定+页面跳转
     */

    //登录
    @PostMapping("/login")
    public ModelAndView login(Long cusTelno, String cusPassword, HttpSession session){
        ModelAndView mav = new ModelAndView();
        Customer customer = loginAndRegisterService.login(cusTelno,cusPassword);
        if (customer != null){
            session.setAttribute("loginCustomer",customer);
            mav.setViewName("redirect:/index");
        }else {
            mav.addObject("loginMsg","用户名或密码错误");
            mav.setViewName("users/login");
        }

        return mav;
    }

    //退出
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("loginCustomer");
        return "redirect:index";
    }

    @PostMapping("/register")
    public ModelAndView register(Customer customer){
        ModelAndView mav = new ModelAndView();
        ServerResponse serverResponse = loginAndRegisterService.register(customer);
        if (serverResponse.getCode() == 200){
            mav.setViewName("users/login");
        }else {
            mav.addObject("registerMsg", "用户名或手机号已被注册！");
            mav.setViewName("users/register");
        }
        return mav;
    }
}
